package com.mlxg.master.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlxg.master.domain.HzReviewTypeReceive;
import com.mlxg.master.mapper.HzReviewTypeReceiveMapper;
import com.mlxg.master.service.IHzReviewTypeReceiveService;
import com.mlxg.selver.domain.HzReviewIdMapping;
import com.mlxg.selver.domain.HzReviewTypeSlave;
import com.mlxg.selver.service.IHzReviewIdMappingService;
import com.mlxg.selver.service.IHzReviewTypeSlaveService;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtils;
import com.mlxg.untils.oss.GeneralOSSUpLoadUtilss;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
@DS("master")
public class HzReviewTypeReceiveServiceImpl extends ServiceImpl<HzReviewTypeReceiveMapper, HzReviewTypeReceive> implements IHzReviewTypeReceiveService {

    @Autowired
    private GeneralOSSUpLoadUtils generalOSSUpLoadUtils;
    @Autowired
    private HzReviewTypeReceiveMapper hzReviewTypeReceiveMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private IHzReviewTypeSlaveService hzReviewTypeSlaveService;
    @Autowired
    private IHzReviewIdMappingService iHzReviewIdMappingService;

    @Override
    public void transferHzHzReviewTypeReceive() {

        int pageSize = 1000;
        int pageNum = 1;
        int totalProcessed = 0;
        int totalSuccess = 0;
        int totalFailed = 0;
        int totalPageFailed = 0;
        log.info("开始往届展会回顾详情数据迁移，每页处理 {} 条记录", pageSize);

        QueryWrapper<HzReviewTypeReceive> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", "0");

        Map<String, HzReviewIdMapping> reviewIdMappingMap = new ConcurrentHashMap<>();
        List<HzReviewTypeReceive> hzReviewTypeReceiveList =null;

        do {
            try {
                Page<HzReviewTypeReceive> page = new Page<>(pageNum, pageSize);
                hzReviewTypeReceiveList = hzReviewTypeReceiveMapper.selectPage(page, queryWrapper).getRecords();

                if (CollectionUtil.isEmpty(hzReviewTypeReceiveList)) {
                    log.info("分页查询完成，没有更多数据，共处理 {} 页", pageNum - 1);
                    break;
                }

                totalProcessed += hzReviewTypeReceiveList.size();
                log.info("开始处理第 {} 页数据，当前页记录数: {}", pageNum, hzReviewTypeReceiveList.size());

                int pageSuccess = 0;
                int pageFailed = 0;

                for (HzReviewTypeReceive oldHzReviewType : hzReviewTypeReceiveList) {
                    try {
                        HzReviewTypeSlave newHzReviewTypeSlave = modelMapper.map(oldHzReviewType, HzReviewTypeSlave.class);

                        String hzReviewId = oldHzReviewType.getHzReviewId();
                        if (StringUtils.isEmpty(hzReviewId)) {
                            throw new RuntimeException("往届回顾ID为空，数据ID: " + oldHzReviewType.getId());
                        }

                        HzReviewIdMapping hzReviewIdMapping = reviewIdMappingMap.computeIfAbsent(hzReviewId,
                                key -> iHzReviewIdMappingService.getById(key));

                        if (hzReviewIdMapping == null) {
                            throw new RuntimeException("未找到往届展会回顾ID映射关系，hzReviewId: " + hzReviewId);
                        }

                        newHzReviewTypeSlave.setHzReviewId(hzReviewIdMapping.getNewHzReviewId());
                        newHzReviewTypeSlave.setDelFlag(0);
                        newHzReviewTypeSlave.setAuditFlag(0);

                        // 处理附件字段
                        if (StringUtils.isNotBlank(oldHzReviewType.getColumn15())) {
                            newHzReviewTypeSlave.setExproAttachment(processUrlFields(oldHzReviewType.getColumn15(), "reviewImgTypes"));
                        }

                        // 处理 typeContent HTML 图片
                        if (StringUtils.isNotBlank(oldHzReviewType.getTypeContent())) {
                            String typeContent = processTypeContentImages(oldHzReviewType.getTypeContent());
                            newHzReviewTypeSlave.setTypeContent(typeContent);
                        }

                        boolean insertSuccess = hzReviewTypeSlaveService.save(newHzReviewTypeSlave);
                        if (insertSuccess) {
                            pageSuccess++;
                            totalSuccess++;
                        }

                    } catch (Exception e) {
                        pageFailed++;
                        totalFailed++;
                        log.error("处理单条记录失败 - 数据ID: {}, 错误信息: {}", oldHzReviewType.getId(), e.getMessage(), e);
                    }
                }

                log.info("第 {} 页数据处理完成 - 成功: {}, 失败: {}", pageNum, pageSuccess, pageFailed);
                pageNum++;

            } catch (Exception e) {
                totalPageFailed++;
                log.error("处理第 {} 页数据失败，错误信息: {}", pageNum, e.getMessage(), e);
                pageNum++;
            }
        } while (hzReviewTypeReceiveList != null && hzReviewTypeReceiveList.size() == pageSize);

        log.info("往届展会回顾数据迁移完成！总处理记录数: {}, 成功: {}, 失败: {}, 失败页数: {}",
                totalProcessed, totalSuccess, totalFailed, totalPageFailed);
    }

    private  String processUrlFields(String fieldValue, String ossDir) {
        if (StringUtils.isBlank(fieldValue)) return null;

        String[] parts = fieldValue.split("\\|+");
        List<String> urls = new ArrayList<>();

        for (String part : parts) {
            if (StringUtils.isBlank(part)) continue;

            String trimmedPart = part.trim();
            try {
                String url = generalOSSUpLoadUtils.uploadUrlToOss(trimmedPart, ossDir);
                if (StringUtils.isNotBlank(url)) urls.add(url);
            } catch (Exception e) {
                log.error("上传文件失败，跳过: {}", trimmedPart, e);
            }
        }

        return urls.isEmpty() ? null : String.join(",", urls);
    }

    private String processTypeContentImages(String typeContent) {
        Document doc = Jsoup.parse(typeContent);
        Elements imgElements = doc.select("img");

        for (Element imgElement : imgElements) {
            String src = imgElement.attr("src");
            if (StringUtils.isNotBlank(src)) {
                try {
                    String newSrc = generalOSSUpLoadUtils.uploadUrlToOss(src, "reviewImgTypeContent");
                    if (StringUtils.isNotBlank(newSrc)) {
                        typeContent = typeContent.replace(src, newSrc);
                    } else {
                        log.warn("处理后的 URL 为空或无效，跳过图片 src: {}", src);
                    }
                } catch (Exception e) {
                    log.error("处理 typeContent 图片失败，src: {}", src, e);
                }
            }
        }
        return typeContent;
    }

//    public static void main(String[] args) {
//        String str = "|/hz/userfiles/1/files/exh/hzReviewType/files/2018/12/16届展会招展书.pdf|/hz/userfiles/1/files/exh/hzReviewType/files/2018/12/第十六届展会回顾.docx";
//        String s = processUrlFields(str,"reviewImgTypesss" );
//    }
}
